package com.hama.zea.xml;

import java.util.Iterator;
import javax.swing.tree.*;
import java.io.File;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 从外存储器读入xml文件并转化为树结构,这样在以后需要建立树结构时无需使用API一层层的建立树结构，只需要将树结构组织为xml文件，导入xml文件即可
 */
public class XML2Tree {
	private DefaultMutableTreeNode treeroot;
	private Element root;

	/**
	 * xmltree类的构造函数，通过一个符合标准的xml文件来初始化xmlTree对象
	 */
	public XML2Tree(File xmlFile) {
		SAXReader reader = new SAXReader();
		Document doc = null;
		try {
			doc = reader.read(xmlFile);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		root = doc.getRootElement();
		treeroot = new DefaultMutableTreeNode(root.getText());
	}

	/**
	 * 通过提供合法的xml文件的路径字符串来初始化xmlToTree对象
	 */
	public XML2Tree(String xmlFilePath) {
		SAXReader reader = new SAXReader();
		Document doc = null;
		try {
			doc = reader.read(new File(xmlFilePath));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		root = doc.getRootElement();
		treeroot = new DefaultMutableTreeNode(root.getText());
	}

	/**
	 * 将xml文件中某一元素作为根节点，创建一个在传入的结点参数上由该元素全部子元素构成的树，要求传入一个元素和结点
	 */
	public static void createtree(Element ele, DefaultMutableTreeNode node) {
		Iterator iter = ele.elementIterator();
		while (iter.hasNext()) {
			Element e = (Element) iter.next();
			DefaultMutableTreeNode childnode = new DefaultMutableTreeNode(
					e.getText());
			node.add(childnode);
			createtree(e, childnode);
		}
	}

	/**
	 * 创建树，并返回根节点
	 */
	public DefaultMutableTreeNode gettreeroot() {
		createtree(root, treeroot);
		return treeroot;
	}
	

}
